package cn.jdy.plugins.service;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.plugins.entity.Download;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @title : 我的下载实现类
 * @description :
 */
@Service
public class DownloadService extends BaseDao<Download> {


	/**
	 * 判断用户是否已经下载此文档
	 * @param userId
	 * @param docId
	 * @return
	 */
	public boolean isDownload(String userId, long docId) {
		return super.count("userId", userId, "docId", docId) > 0;
	}

	/**
	 * 按条件查询
	 * @param download
	 * @return
	 */
	public List<Download> query(Download download) {
		if(download == null) return super.findAll();
		DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
		dc.add(Restrictions.eq("userId", download.getUserId()));
		return super.find(dc, download.getiDisplayStart(), download.getiDisplayLength());
	}

	public Long count(Download download) {

		return super.count("userId", download.getUserId());
	}

	/**
	 * 增加一次 下载次数
	 *
	 * @param userId
	 * @param docId
	 */
	@Transactional
	public void addOneTime(String userId, long docId) {
		try {
			Query query = super.em().createSQLQuery("update download t set t.count = t.count + 1 where t.userId = :userId and t.docid = :docid");
			query.setParameter("userId", userId);
			query.setParameter("docid", docId);
			query.executeUpdate();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "addOneTime", e);
		}
	}

	/**
	 * 个人中心下载文章列表
	 * @param entity
	 * @return
	 */
  public List<Download> queryWapList(Download download){
    StringBuilder sql = new StringBuilder("SELECT a.id,a.docId,a.createTime,summary FROM download a,doc b WHERE a.userId=?  AND a.docId=b.id");
    sql.append(" ORDER BY createTime DESC limit ?,?");
    Query query = super.em().createSQLQuery(sql.toString());
    // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题 
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    query.setParameter(0, download.getUserId());
    query.setParameter(1, download.getiDisplayStart());
    query.setParameter(2, download.getiDisplayLength());
    return query.list();
  }
  
}
